package com.gupao.vip.converter;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.Properties;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.gupao.vip.controller.Person;

/**
 * Created by 17082655 on 2019/1/7.
 */
public class PropertiesPersonHttpMessageConverter extends AbstractHttpMessageConverter<Person> {
	public PropertiesPersonHttpMessageConverter() {
		//设置媒体类型
		super(MediaType.valueOf("application/properties+person"));
		setDefaultCharset(Charset.forName("UTF-8"));
	}

	@Override
	protected boolean supports(Class<?> clazz) {
		//只支持person的父类或接口
		return clazz.isAssignableFrom(Person.class);
	}

	@Override
	protected Person readInternal(Class<? extends Person> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
		InputStream in = httpInputMessage.getBody();
		Properties pro = new Properties();
		pro.load(new InputStreamReader(in,getDefaultCharset()));
		//将properties内容转化到person对象中
		Person person = new Person();
		person.setId((pro.getProperty("person.id")));
		person.setName(pro.getProperty("person.name"));
		return person;
		
	}

	@Override
	protected void writeInternal(Person person, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
		OutputStream out = httpOutputMessage.getBody();
		Properties p = new Properties();
		p.setProperty("person.id",String.valueOf(person.getId()));
		p.setProperty("person.name",person.getName());
		p.store(new OutputStreamWriter(out,getDefaultCharset()),"written by web server");
	}
}
